import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Dashboard from '@/views/dashboard'
import Article from '@/views/article'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        component: Dashboard
      },
      {
        path: '/article',
        component: Article
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加一个路由的前置守卫，实现页面的访问拦截
// to: 去哪里
// from: 从哪儿来
// next: 是否放行
// next() ==> 放行 ==> 就不会再次进入路由前置守卫了
// next(地址) ==> 跳转到指定地址 ==> 会重新进入前置守卫
router.beforeEach((to, from, next) => {
  // 如果用户没有登录，那么就只能待在登录页面
  // 如果用户登录了，那么哪儿都可以去
  if (store.getters.token || to.path === '/login') {
    next()
    return
  }
  next('/login')
})
export default router
